package com.ygxsk.carhome.ui.usercenter;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.event.EventInfo;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.ClearEditText;
import com.ygxsk.carhome.views.MaxLengthWatcher;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @date 2018/1/11 0011
 * @auther itchenqi
 * @description 个人中心--我的资料信息---修改昵称等编辑单条信息界面
 */
public class MyInfoModifyActivity extends ErrorActivity {

    @BindView(R.id.edittextcontent)
    ClearEditText edittextcontent;

    /**
     * 设置默认的hint的包裹内容
     */
    private int flag_title;
    private Session mSession;
    private AlertView mAlertView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        mSession = Session.get(MyInfoModifyActivity.this);

        initViews();

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    public Resources getResources() {
        return super.getResources();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_nice_name_modify;
    }


    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setLayoutSao(false, null);
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_title = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            if (flag_title == 0) {//设置昵称
                toolbarHelper.setTitle("设置昵称");
            } else if (flag_title == 1) {//
                toolbarHelper.setTitle("设置职业");
            } else if (flag_title == 2) {//
//                toolbarHelper.setTitle("兴趣爱好");
            } else if (flag_title == 3) {
                toolbarHelper.setTitle("姓名");
            } else {
                toolbarHelper.setTitle("编辑资料");
            }

        } else {
            toolbarHelper.setTitle("编辑资料");
        }

        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkEdit();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutRight(true, 1, "保存", new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //ToastUtils.showShort("测试保存");
                //在这里添加接口内容。因为假如失败了，重新写等。

                //这里添加上网络判断，断网保存不了 也没有提示，不友好

                if (NetworkUtils.isConnected()) {

                    String content = edittextcontent.getText().toString().trim();

                    if (!TextUtils.isEmpty(content)) {
                        method_updateCustomerInfo(content);
                    } else {
                        ToastUtils.showShort(R.string.contentnulldata);
                    }

                } else {

                    ToastUtils.showShort(ConstantSign.NONET);

                }

            }
        });


    }

    /**
     * 仅仅是做
     */
    private final ApiRequestSubListener apiRequestSubListener = new ApiRequestSubListener(ConstantApi.IS_ACTIVITY_ITSELF, MyInfoModifyActivity.this) {

        @Override
        public void onErrorServerNotSuccessDataResponse(int method, boolean isToastToUser, Activity activity, String statusCode, String message) {
            super.onErrorServerNotSuccessDataResponse(method, isToastToUser, activity, statusCode, message);

            //.没有其他接口，直接
            //LogUtils.d("itchen--->子类执行了onErrorServerResponse------" + message);

            ToastUtils.showShort(message);

        }
    };

    private void method_updateCustomerInfo(String contentPass) {

        HashMap<String, Object> map = new HashMap<>();

        map.put(Parameterkey.customerId, mSession.getCustomerId());//用户id信息

        if (flag_title == 0) {//设置昵称
            //toolbarHelper.setTitle("设置昵称");
            map.put(Parameterkey.nickName, contentPass);

        } else if (flag_title == 1) {//
            //toolbarHelper.setTitle("设置职业");
            map.put(Parameterkey.occupation, contentPass);

        } else if (flag_title == 2) {//
            //toolbarHelper.setTitle("兴趣爱好");
//            map.put(Parameterkey.hobby, contentPass);

        } else if (flag_title == 3) {//设置真实姓名

            map.put(Parameterkey.trueName, contentPass);

        } else {
            //toolbarHelper.setTitle("编辑资料");
            //map.put("hobby",contentPass);
        }


        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECUSTOMERINFO);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateCustomerInfoUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateCustomerInfo(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                .compose(MyInfoModifyActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, apiRequestSubListener))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        //LogUtils.d("itchen---->依然执行了MyInfoModify内部");

                        //正常提示 更新成功的信息
                        //其实应用的昵称此时已经变化了。是否要调用一次登录接口重新存？？？？？

                        String editContent = edittextcontent.getText().toString().trim();

                        if (flag_title == 0) {//设置昵称

                            mSession.setNickName(editContent);
                            //2018年03月26日不添加发送
                            RxBus.getInstance().post(new EventInfo(ConstantApi.RXBUS_MODIFY_NICKNAME, editContent));


                        } else if (flag_title == 1) {//设置职业
                            mSession.setOccupation(editContent);
                            RxBus.getInstance().post(new EventInfo(flag_title, editContent));

                        } else if (flag_title == 2) {//设置兴趣爱好

//                            mSession.setHobby(editContent);
//                            RxBus.getInstance().post(new EventInfo(flag_title, editContent));

                        } else if (flag_title == 3) {

                            mSession.setTrueName(editContent);
                            RxBus.getInstance().post(new EventInfo(flag_title, editContent));
                        }

                        methodBack();
                    }

                    //自定义

                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {


                    }
                });

    }


    @Override
    public void onClickNodata(View v) {

        //retain这个暂时不需要

    }

    @Override
    public void initViews() {

        Bundle bundleExtra = this.getIntent().getExtras();

        if (bundleExtra != null) {

            String extra_content = bundleExtra.getString(ExtraKey.EXTRA_JUMPFROM_CONTENT);

            //edittextcontent.setHint();
            if (flag_title == 0) {//设置昵称

                //这里还可能从上一个界面携带有编辑数据
                //并且这个也会在本地存一份，直接取本地存的那一份就行
                edittextcontent.setHint("请填写昵称");
                CommUtils.setText(edittextcontent, extra_content);
                //这个特殊因为默认昵称是手机号码
                edittextcontent.addTextChangedListener(new MaxLengthWatcher(ConstantApi.MAXLENEDITTEXT, edittextcontent, getString(R.string.textstring12length)));

            } else if (flag_title == 1) {//

                edittextcontent.setHint("请填写职业");
                CommUtils.setText(edittextcontent, extra_content);
                //字符无限制


            } else if (flag_title == 2) {//
                edittextcontent.setHint("请填写兴趣爱好，以逗号隔开");
                CommUtils.setText(edittextcontent, extra_content);

            } else {
                edittextcontent.setHint("请输入文本内容");
                CommUtils.setText(edittextcontent, extra_content);

            }


        }

    }

    @Override
    public void gainDatas() {

        //retain

    }


    private void checkEdit() {

        if (KeyboardUtils.isSoftInputVisible(MyInfoModifyActivity.this)) {
            KeyboardUtils.hideSoftInput(MyInfoModifyActivity.this);
        }

        if (!TextUtils.isEmpty(edittextcontent.getText().toString())) {

            CommUtils.checkDialog(mAlertView);

            mAlertView = new AlertView(ConstantSign.ALERT_TITLE,
                    "退出此次编辑?",
                    "取消",
                    new String[]{"退出"},
                    null,
                    MyInfoModifyActivity.this,
                    AlertView.Style.Alert,
                    new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                methodBack();

                            }

                        }
                    });

            mAlertView.setCancelable(true).show();


        } else {
            methodBack();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (KeyboardUtils.isSoftInputVisible(MyInfoModifyActivity.this)) {
            KeyboardUtils.hideSoftInput(MyInfoModifyActivity.this);
        }

        if (mAlertView != null) {
            if (mAlertView.isShowing()) {
                mAlertView.dismiss();
                mAlertView = null;
            }
        }

    }

    @Override
    public void methodBack() {

        if (KeyboardUtils.isSoftInputVisible(MyInfoModifyActivity.this)) {
            KeyboardUtils.hideSoftInput(MyInfoModifyActivity.this);
        }

        ActivityUtils.finishActivity(MyInfoModifyActivity.this);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            checkEdit();

            return true;

        }

        return super.onKeyDown(keyCode, event);
    }
}
